<?php

namespace Lib;

class Server {

	public function init() {
		global $_CONFIG;
		$sDocumentRoot = str_replace ( '\\', '/', $_SERVER ['DOCUMENT_ROOT'] );
		$sRoot = str_replace ( '\\', '/', ROOT );
		if (! $_CONFIG ['base'] ['site_url']) {
			$sUrl = $_SERVER ['SERVER_PORT'] == 443 ? 'https://' : 'http://';
			$sUrl .= $_SERVER ['HTTP_HOST'];
			$sUrl .= $_SERVER ['SERVER_PORT'] != 80 && $_SERVER ['SERVER_PORT'] != 443 ? ':' . $_SERVER ['SERVER_PORT'] : '';
			$_CONFIG ['base'] ['site_url'] = str_replace ( $sDocumentRoot, $sUrl, $sRoot );
		}
		if (! $_CONFIG ['base'] ['host']) {
			$_CONFIG ['base'] ['host'] = $_SERVER ['HTTP_HOST'];
		}
		if (! $_CONFIG ['base'] ['path']) {
			$_CONFIG ['base'] ['path'] = str_replace ( $sDocumentRoot, '', $sRoot );
		}
		if (preg_match ( '/^http/i', $_SERVER ['SERVER_PROTOCOL'] )) {
			$_CONFIG ['base'] ['http'] = true;
		} else {
			$_CONFIG ['base'] ['http'] = false;
		}
		return $_CONFIG ['base'] ['http'];
	}

	public function getUrl() {
		$sUrl = $_SERVER ['SERVER_PORT'] == 443 ? 'https://' : 'http://';
		$sUrl .= $_SERVER ['HTTP_HOST'];
		$sUrl .= $_SERVER ['SERVER_PORT'] != 80 && $_SERVER ['SERVER_PORT'] != 443 ? ':' . $_SERVER ['SERVER_PORT'] : '';
		return $sUrl;
	}

	public function getSearch($sException = null) {
		if (is_array ( $_GET )) {
			$aGet = $_GET;
			if (is_array ( $sException )) {
				foreach ( $sException as $sKey => $sRow ) {
					if (is_string ( $sKey )) {
						$aGet [$sKey] = $sRow;
					} elseif ($sRow == null) {
						unset ( $aGet [$sKey] );
					} else {
						unset ( $aGet [$sRow] );
					}
				}
			} elseif ($sException) {
				unset ( $aGet [$sException] );
			}
			$aResult = array ();
			foreach ( $aGet as $sKey => $sRow ) {
				$aResult [] = $sKey . '=' . urlencode ( $sRow );
			}
			return implode ( '&', $aResult );
		} else {
			return '';
		}
	}

	public function location($sUrl) {
		header ( 'location:' . $sUrl );
		exit ();
	}

	public function getInputFromSearch($sException = null) {
		if (is_array ( $_GET )) {
			$aGet = $_GET;
			$sInput = null;
			if (is_array ( $sException )) {
				foreach ( $sException as $sKey => $sRow ) {
					if (is_string ( $sKey )) {
						$aGet [$sKey] = $sRow;
					} elseif ($sRow == null) {
						unset ( $aGet [$sKey] );
					} else {
						unset ( $aGet [$sRow] );
					}
				}
			} elseif ($sException) {
				unset ( $aGet [$sException] );
			}
			foreach ( $aGet as $sKey => $sRow ) {
				$sInput .= '<input type="hidden" name="' . $sKey . '" value="' . $sRow . '">';
			}
			return $sInput;
		} else {
			return '';
		}
	}
}

?>